package com.vhall.component.framework.common.exception;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;

/**
 * 错误码对象
 * 全局错误码，占用 [0, 999], 参见 {@link GlobalErrorCode}
 * 业务异常错误码，占用 [1 000 000 000, +∞)，参见 {@link BizErrorCode}
 * * TODO 错误码设计成对象的原因，为未来的 i18 国际化做准备
 *
 * @author yongzheng.xu
 * @date 2021/5/22 20:58
 */
@Slf4j
@Data
public class ErrorCode {

    private static JSONObject jb;

    static {
        try {
            ClassPathResource classPathResource = new ClassPathResource("code.json");
            InputStream stream = classPathResource.getInputStream();
            byte[] bytes = IoUtil.readBytes(stream, true);
            String codes = new String(bytes);
            jb = new JSONObject(codes);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }

    /**
     * 错误码
     */
    private final Integer code;
    /**
     *
     */
    private final String key;
    /**
     * 错误提示
     */
    private final String msg;

    public ErrorCode(Integer code, String key) {
        this.code = code;
        this.msg = jb.getStr(key);
        this.key = key;
    }

}
